package testDemo;

import java.util.Arrays;

/**
 * @author : zzr
 * @description :
 * @date :
 */
public class MyArrayList {
    private int[] elem;
    private int usedSize;

    public static final int DEFAULT_SIZE = 10;

    public MyArrayList() {
        this.elem = new int[DEFAULT_SIZE];
    }

    public MyArrayList(int size) {
        this.elem = new int[size];
    }

    public void display() {
        for (int i = 0; i < this.usedSize; i++) {
            System.out.print(this.elem[i] + " ");
        }
        System.out.println();
    }

    public void add(int data) {
        if(isFull()) {
            this.elem = Arrays.copyOf(this.elem,this.elem.length * 2);
        }
        this.elem[usedSize] = data;
        usedSize++;
    }

    private boolean isFull() {
        if (this.elem.length == usedSize) {
            return true;
        }
        return false;
    }

    /**
     * 在指定位置pos上插入元素data
     * @param data
     * @param pos
     */
    public void add(int data, int pos) {
        if(pos < 0 || pos > usedSize) {
//            System.out.println("输入的位置不合法");
//            return;
            throw new PostOutOfRange("输入的位置不合法");
        }
        if(isFull()) {
            this.elem = Arrays.copyOf(this.elem, this.elem.length * 2);
        }
        for (int i = usedSize - 1; i >= 0; i--) {
            elem[i + 1] = elem[i];
        }
        elem[pos] = data;
        usedSize++;
    }

    /**
     * 顺序表中是否包含某元素
     * @param toFind
     * @return
     */
    public boolean contains(int toFind) {
        for (int i = 0; i < usedSize; i++) {
            if(toFind == elem[i]) {
                return true;
            }
        }
        return false;
    }
}
